﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using KV_ISO14443;
using System.IO.Ports;
using System.Threading;
using System.Data.SqlClient;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        private SqlConnection master;//定义数据连接对象
        private SqlCommand cmd;//定义数据命令对象
        private SqlDataAdapter sqlada;//定义数据适配器对象
        private SqlCommandBuilder sqlbuid;//定义CommandBuilder对象
        private DataSet ds;//定义数据集对象

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //获取当前计算机的串口号数组
            string[] strPortNum = System.IO.Ports.SerialPort.GetPortNames();

            //如果数组strPortNum的长度小于1，说明没有连接串口
            if (strPortNum.Length < 1)
            {
                MessageBox.Show("没有连接串口！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                foreach (string s in strPortNum)
                {
                    if (s.Length < 7)
                    {
                        cmbPort.Items.Add(s);
                    }
                }
                cmbPort.SelectedIndex = 0;
            }

        }

        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            if (btnOpenPort.Text.Equals("打开串口"))
            {
                OpenSerialPort();
            }
            else
            {
                CloseSerialPort();
            }      
        }
        public void OpenSerialPort()
        {
            if (cmbPort.Text.Equals(""))
            {
                MessageBox.Show("没有选择串口，请选择串口！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //调用OpenSerialPort方法打开串口，如果返回值不等于0x00，说明串口打开失败；反之，串口打开成功
            if (FR102.OpenSerialPort(cmbPort.Text) != 0x00)
            {
                MessageBox.Show(String.Format("串口{0}打开失败！", cmbPort.Text), "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                MessageBox.Show(String.Format("串口{0}打开成功！", cmbPort.Text), "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            //检测并连接设备
            if (FR102.TestReader() != 0x00)
            {
                MessageBox.Show(String.Format("没有检测到连接到串口{0}的设备，请检查与设备连接的串口！", cmbPort.Text),
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (FR102.CloseSerialPort() == 0x00)
                {
                    MessageBox.Show(String.Format("串口{0}关闭成功！", cmbPort.Text), "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                return;
            }

            //重新启动读写器
            if (FR102.RestartReader() != 0x00)
            {
                MessageBox.Show("设备启动失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //设置波特率方法默认为 9600
            if (FR102.ChangeBaudRate(Int32.Parse("9600")) != 0x00)
            {
                MessageBox.Show("修改串口波特率失败！");
                return;
            }

            btnOpenPort.Text = "关闭串口";
            cmbPort.Enabled = false;
            btnAccessCardNum.Enabled = true;
        }
        private void CloseSerialPort()
        {
            //如果CloseSerialPort（）方法的返回值等于0x00，说明串口关闭成功；反之，串口关闭失败
            if (FR102.CloseSerialPort() == 0x00)
            {
                MessageBox.Show(String.Format("关闭串口:串口{0}关闭成功！", cmbPort.Text.Trim()),
                        "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                btnOpenPort.Text = "打开串口";
                cmbPort.Enabled = true;
                txtCardNum.Enabled = false;
             }
            else
            {
                MessageBox.Show(String.Format("关闭串口:串口{0}关闭失败！", cmbPort.Text.Trim()),
                        "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        private void btnAccessCardNum_Click(object sender, EventArgs e)
        {
            string cardID;
            byte[] TagType;
            byte[] TagNumber;

            //寻天线区内所有卡,得到卡类型
            FR102.StatusCode ec = FR102.PcdRequest(0x52, out TagType);
            if (ec == FR102.StatusCode.AllDone)
            {
                //防冲撞，得到卡号
                FR102.StatusCode ec2 = FR102.PcdAnticoll2(out TagNumber);
                //将数组TagNumber转换为字符串
                cardID = Converter.ArrayToHexStr(TagNumber);

                if (cardID == "00000000")
                {
                    cardID = "";
                }

                //将字符串转cardID换为数组
                byte[] TagNumber2 = Converter.HexStrToArray(cardID);
                //选定卡片
                FR102.StatusCode ec3 = FR102.PcdSelect(TagNumber2);

                txtCardNum.Text = cardID;

              
            }
        }
        private void btnClosePort_Click(object sender, EventArgs e)
        {
            CloseSerialPort();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string sex = "";
            if (radioButton1.Checked)
            {
                sex = "男";
            }
            else
            {
                sex = "女";
            }
            string connString = "Data Source=(localdb)\\Projects;Initial Catalog=TEST;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";
            string sqlString = "insert into student(sno,sname,RFIDNumber,sex,college,room)values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + sex + "','" + textBox4.Text + "','" + textBox12.Text + "')";
            master = new SqlConnection(connString);//建立连接对象
            master.Open();
            cmd = new SqlCommand(sqlString, master);//建立数据命令对象
            cmd.ExecuteNonQuery();
            MessageBox.Show("记录成功！");
            textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";//清空各文本框

        }

        private void button5_Click(object sender, EventArgs e)
        {
            string connString = "Data Source=(localdb)\\Projects;Initial Catalog=TEST;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";
            string sqlString = "SELECT sname AS 姓名,RFIDNumber AS 射频卡号,sex AS 性别,college AS 所在院系,room AS 宿舍号 FROM student where RFIDNumber='" + textBox5.Text + "'";

            master = new SqlConnection(connString);
            master.Open();//打开连接
            sqlada = new SqlDataAdapter(sqlString, master);
            sqlbuid = new SqlCommandBuilder(sqlada);
            ds = new DataSet();
            sqlada.Fill(ds, "student");//填充数据集ds
            dataGridView1.DataSource = ds.Tables["student"];
        }

        private void button3_Click(object sender, EventArgs e)
        {
            sqlada.Update(ds.Tables["student"]);//更新数据源
            MessageBox.Show("修改数据成功！");

        }

        private void button6_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Remove(dataGridView1.CurrentRow);//删除当前行
            sqlada.Update(ds.Tables["student"]);
            MessageBox.Show("删除记录成功！");

        }

    }
}
